// 在 store 中创建一个模块（WebSocket 模块）
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
import { Notification } from 'element-ui';
import { getToken } from "@/utils/auth";

const state = {
  stompClient: null,
  heartCheckTimer: null,
  messages: {}
};

const mutations = {
  SET_STOMP_CLIENT(state, client) {
    state.stompClient = client;
  },
  CLEAR_STOMP_CLIENT(state) {
    state.stompClient = null;
  },
  SET_HEART_CHECK_TIMER(state, timer) {
    state.heartCheckTimer = timer;
  },
  ADD_MESSAGE(state, message) {
    state.messages = message; 
  },
};

const actions = {
  startWebSocket({ commit, dispatch, state }) {
    if (getToken() && (!state.stompClient || state.stompClient.connected === false)) {
      console.log("SOCKET_PATH:", process.env);
      const socketUrl = `http://localhost:8080/ws`;
      const socket = new SockJS(socketUrl);
      const stompClient = Stomp.over(socket);
      stompClient.connect({}, frame => {
        console.log(`${new Date().toLocaleString()} >>>>> 连接成功`, frame);
        Notification({
          type: "success",
          title: '成功',
          message: '身份证读卡器连接成功',
          position: "top-right",
          duration: 3000,
          showClose: true
        });
        // 保存 STOMP 连接信息
        commit('SET_STOMP_CLIENT', stompClient);
        // 订阅消息
        stompClient.subscribe('/topic/realtime', e => {
          const message = e.body; 
          console.log("🚀 ~ startWebSocket ~ message:", message)
          commit('ADD_MESSAGE', message); // 将消息添加到 Vuex 中
          if (message.content !== "pong") {
            Notification({
              type: "info",
              title: '身份证读取成功',
              message: message.content,
              position: "top-right",
              duration: 3000,
              showClose: true
            });
          }
        });
        // 开始心跳检测
        dispatch('startHeartCheck');
      }, error => {
        console.log(`${new Date().toLocaleString()} >>>>> 数据传输发生异常`, error);
        // Notification({
        //   type: "error",
        //   title: '错误',
        //   message: '身份证取卡器链接异常',
        //   position: "top-right",
        //   duration: 3000,
        //   showClose: true
        // });
        dispatch('reconnectWebSocket');
      });
    }
  },

  sendWebSocketMessage({ state }, msg) {
    console.log(`${new Date().toLocaleString()} >>>>> 发送消息：${msg}`, state.stompClient);
    if (state.stompClient && state.stompClient.connected) {
      state.stompClient.send("/app/messages", {}, JSON.stringify({ 'content': msg }));
    } else {
      console.error("WebSocket 连接未建立");
    }
  },

  reconnectWebSocket({ dispatch }) {
    dispatch('clearWebSocket');
    // 递归调用，一直尝试重连
    setTimeout(() => {
      dispatch('startWebSocket');
    }, 6000);
  },

  clearWebSocket({ commit, state }) {
    if (state.stompClient) {
      state.stompClient.disconnect(() => {
        commit('CLEAR_STOMP_CLIENT');
        commit('CLEAR_MESSAGES'); // 清空消息数组
      });
    }
  },

  startHeartCheck({ commit, dispatch, state }) {
    console.log(`${new Date().toLocaleString()} >>>>> 开始心跳检测`, state.stompClient);
    // 清除之前的计时器
    dispatch('clearHeartCheckTimer');

    // 创建新的计时器
    const timer = setInterval(() => {
      if (!state.stompClient || state.stompClient.connected === false) {
        console.log(`${new Date().toLocaleString()} >>>>> 心跳检测失败,触发重连`, state.stompClient);
        dispatch('reconnectWebSocket');
      } else {
        console.log(`${new Date().toLocaleString()} >>>>> 心跳正常,继续下一次心跳检测`, state.stompClient);
        dispatch('sendWebSocketMessage', 'ping');
      }
    }, 1000 * 29);
    commit('SET_HEART_CHECK_TIMER', timer);
  },

  clearHeartCheckTimer({ commit, state }) {
    const timer = state.heartCheckTimer;
    timer && clearInterval(timer);
    commit('SET_HEART_CHECK_TIMER', null);
  },

  CLEAR_MESSAGES(state) {
    state.messages = []; // 清空消息数组
  }
};


export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
